//
//  DeviceListVC.m
//  Holyiot-DFU
//
//  Created by bill on 2021/2/23.
//

#import "DeviceListVC.h"
#import "DeviceListCell.h"
#import "BluetoothCenter.h"

#import "LbSlider.h"
#import "TempTarget.h"
#import "UIBarButtonItem+add.h"
#import "SystemInfoVC.h"
#import "BLEFilterVC.h"

#import "BluetoothCenter+Editor.h"
#import <UIViewController+MMDrawerController.h>
@interface DeviceListVC ()<UITableViewDelegate,UITableViewDataSource,BluetoothCenterDelegate>{
    
}
@property(nonatomic, strong)NSArray *beaconArr;//存放扫描的iBeacon的数组
@property(nonatomic,strong)NSTimer *timer;


@property (weak, nonatomic) IBOutlet UITextField *searchTFD;


@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,copy)NSArray *devicesArr;
@property (weak, nonatomic) IBOutlet UITextField *textfield;

@property (weak, nonatomic) IBOutlet UITextField *textField;

@property (weak, nonatomic) IBOutlet UIView *shadeView;
@property(nonatomic,copy)NSString *proximityUUID;

@end

@implementation DeviceListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.proximityUUID = @"FDA50693-A4E2-4FB1-AFCF-C6EB07647825";
    self.navigationItem.title = @"Device Scanner";
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"DeviceListCell" bundle:nil] forCellReuseIdentifier:@"deviceListCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"IBeaconCell" bundle:nil] forCellReuseIdentifier:@"IBeaconCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EddystoneCell" bundle:nil] forCellReuseIdentifier:@"EddystoneCell"];
    self.tableView.estimatedRowHeight = 120;
    self.tableView.tableFooterView = [UIView new];
//    [[BluetoothCenter shareInstance]scanperipheral];
    [BluetoothCenter shareInstance].delegate = self;
    UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_search"]];
    imgView.frame = CGRectMake(10, 0, 20, 20);
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
    [leftView addSubview:imgView];
    self.textfield.leftView = leftView;
    self.textfield.leftViewMode = UITextFieldViewModeAlways;
    self.shadeView.layer.cornerRadius = self.textfield.height/2;
    self.shadeView.layer.shadowColor = RGBA(220,220, 220, 1).CGColor;
    self.shadeView.layer.shadowOpacity = 1;
    self.shadeView.layer.shadowOffset = CGSizeMake(0,0);
    self.shadeView.layer.shadowRadius = 3;
//    self.shadeView.layer.masksToBounds = YES;
//    self.shadeView.layer.borderColor = RGBA(230, 230, 230, 1).CGColor;
//    self.shadeView.layer.borderWidth = 1;
   // [self setupBeacon];
//    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithImage:@"ic_zhuyi" ImageHighLight:@"ic_zhuyi" Target:self Seletor:@selector(systemInfo) CGRect:CGRectMake(0, 0, 30, 30)];
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTitle:@"Filter" Target:self Seletor:@selector(filterAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    [self setupLeftBarButtonItem:@"Info"];
}
-(void)setupLeftBarButtonItem:(NSString*)title
{
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTitle:title Target:self Seletor:@selector(systemInfo)];
    self.navigationItem.leftBarButtonItem = leftItem;
}
#pragma mark ------ 系统信息 --------
-(void)systemInfo
{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    
}
-(void)filterAction
{
    BLEFilterVC *filterVC = [[BLEFilterVC alloc]init];
    [self.navigationController pushViewController:filterVC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([BluetoothCenter shareInstance].deviceType == DeviceTypeBeacon) {
       
        [self searchDevice:nil];
        self.searchTFD.placeholder = @"Name/MAC";
        
    }else if ([BluetoothCenter shareInstance].deviceType == DeviceTypeiBeacon){
        [[BluetoothCenter shareInstance]stopScand];
        [self setupBeacon];
        [self setupLeftBarButtonItem: @"iBeacon"];
        self.searchTFD.placeholder = @"UUID";
        NSLog(@"-------111111111");
    }

}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [BluetoothCenter shareInstance].delegate = self;
    if ([BluetoothCenter shareInstance].deviceType != DeviceTypeiBeacon) {
        [self startTimer];
        [self sortByRSSI];
    }else{
        [self stopTimer];
        [self.tableView reloadData];
    }
    
    NSLog(@"-------2222222");
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self stopTimer];
}
-(void)startTimer
{
    if (_timer==nil) {
        _timer = [TempTarget scheduledTimerWithTimeInterval:2 target:self selector:@selector(sortByRSSI) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}
-(void)stopTimer
{
    [_timer invalidate];
    _timer = nil;
}
-(void)updateUI{
    for (DeviceListCell *cell in [self.tableView visibleCells]) {
        NSIndexPath *index =  [self.tableView indexPathForCell:cell];
        cell.peripheral = self.devicesArr[index.row];
    }
}

-(void)setupBeacon
{
    if (self.searchTFD.text.length>0) {
        NSString *uuid = [self.searchTFD.text uppercaseString];
        //先把-去掉
        if ([self.searchTFD.text containsString:@"-"]) {
           uuid = [self.searchTFD.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
        }
        NSString *regularStr = @"[a-f0-9A-F]{32}";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularStr];
        if ([predicate evaluateWithObject:uuid ]==NO) {
            [MBProgressHUD showError:@"Please enter 32 characters"];
            return;
        }
        NSString *str1 = [uuid substringWithRange:NSMakeRange(0, 8)];
        NSString *str2 = [uuid substringWithRange:NSMakeRange(8, 4)];
        NSString *str3 = [uuid substringWithRange:NSMakeRange(12, 4)];
        NSString *str4 = [uuid substringWithRange:NSMakeRange(16, 4)];
        NSString *str5 = [uuid substringWithRange:NSMakeRange(20, uuid.length-20)];
        NSString *finalUUID = [NSString stringWithFormat:@"%@-%@-%@-%@-%@",str1,str2,str3,str4,str5];
       self.proximityUUID = finalUUID;
    }else{
        self.proximityUUID = @"FDA50693-A4E2-4FB1-AFCF-C6EB07647825";
    }
    _beaconArr = [[NSArray alloc] init];
    
   
    
}


#pragma mark -------- 排序 ----------
-(void)sortByRSSI
{
    self.devicesArr = [BluetoothCenter shareInstance].peripherals.copy;
//    //对搜索到的设备进行排序
//    if (self.devicesArr.count>1) {
//        NSArray *result = [self.devicesArr sortedArrayUsingComparator:^NSComparisonResult(CBPeripheral* obj1, CBPeripheral* obj2) {
//            NSDictionary *obj1_dic = [[BluetoothCenter shareInstance].deviceInfo objectForKey:obj1.identifier.UUIDString];
//            NSDictionary *obj2_dic = [[BluetoothCenter shareInstance].deviceInfo objectForKey:obj2.identifier.UUIDString];
////            NSLog(@"%@==%@",obj1_dic,obj2_dic);
//            return [[obj1_dic objectForKey:device_rssi]intValue]<[[obj2_dic objectForKey:device_rssi]intValue];
//        }];
//        self.devicesArr = result.copy;
//
//    }
    NSLog(@"-----排序");
    [self.tableView reloadData];
}

#pragma mark ------- 扫描设备 -----
- (IBAction)searchDevice:(id)sender {
    if ([BluetoothCenter shareInstance].deviceType == DeviceTypeiBeacon) {
        [self setupBeacon];
        return;
    }
    [self.textfield resignFirstResponder];
    self.devicesArr=nil;
    [self.tableView reloadData];
    [BluetoothCenter shareInstance].filterString = self.textfield.text;
    [[BluetoothCenter shareInstance]stopScand];
    [[BluetoothCenter shareInstance]scanperipheral];
}
#pragma mark ------- 滑动条值发生改变 -------

#pragma mark --------  扫描到设备,刷新tableView里可见的cell  ---------
-(void)bluetoothCenterDidScandPeripheral:(CBPeripheral *)peripheral
{
    //[self updateUI];
}
//扫描到新设备,刷新设备列表
-(void)refreshTableView
{
    self.devicesArr = [[BluetoothCenter shareInstance].peripherals copy];
    [self.tableView reloadData];
}
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if ([BluetoothCenter shareInstance].deviceType == DeviceTypeiBeacon) {
//        return 70;
//    }else{
//        return tableView.estimatedRowHeight;
//    }
//}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([BluetoothCenter shareInstance].deviceType == DeviceTypeiBeacon) {
        NSLog(@"---->返回 iBeacon 数组: %d个",self.beaconArr.count);
        return self.beaconArr.count;
    }else{
        NSLog(@"---->返回 beacon & eddystone");
        return self.devicesArr.count;
    }
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    DeviceListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"deviceListCell"];
    CBPeripheral *p = self.devicesArr[indexPath.row];
    cell.peripheral = p;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [self.navigationController pushViewController:[FunctionVC new] animated:YES];
//    return;
//    [MBProgressHUD showDefaultLoadingMessage:@"connecting..."];
    if (indexPath.row > self.devicesArr.count-1) {
        return;
    }
    if ([BluetoothCenter shareInstance].dfu_name.length==0) {
        [MBProgressHUD showError:@"please enter DFU name"];
        return;
    }
    if ([BluetoothCenter shareInstance].dfu_code.length==0) {
        [MBProgressHUD showError:@"please enter DFU code"];
        return;
    }
    if ([[NSFileManager defaultManager]fileExistsAtPath:[BluetoothCenter shareInstance].firmware.fileUrl.path]) {
        [[BluetoothCenter shareInstance]stopScand];
        CBPeripheral *p = self.devicesArr[indexPath.row];
        [[BluetoothCenter shareInstance]connetPeripheral:p];
        [MBProgressHUD showDefaultLoadingMessage:@"prepare for upgrade..."];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD dismiss];
        });
    }else{
        [MBProgressHUD showError:@"file error, please reselect the file"];
    }
    
   
    
    
//    if ([BluetoothCenter shareInstance].deviceType == DeviceTypeBeacon) {
//        CBPeripheral *p = self.devicesArr[indexPath.row];
//        DeviceDetailInfoVC *detailVC = [[DeviceDetailInfoVC alloc]init];
//        detailVC.peripheral = p;
//        [self.navigationController pushViewController:detailVC animated:YES];
//    }
//    if ([BluetoothCenter shareInstance].deviceType == DeviceTypeEddystone) {
//
//         MBProgressHUD *hud = [MBProgressHUD showMessage:@"connecting..." toView:self.view];
//         [hud.button setTitle:@"Cannel" forState:UIControlStateNormal];
//         [hud.button addTarget:self action:@selector(cannelAction) forControlEvents:UIControlEventTouchUpInside];
//         CBPeripheral *p = self.devicesArr[indexPath.row];
//         [[BluetoothCenter shareInstance] connetPeripheral:p];
//    }
//    //切换到Beacon搜索页面
//    if ([BluetoothCenter shareInstance].deviceType == DeviceTypeiBeacon) {
//        [self stopIBeaconMonitor];
//        [[BluetoothCenter shareInstance]stopScand];
//        [BluetoothCenter shareInstance].deviceType = DeviceTypeBeacon;
//        [self searchDevice:nil];
//        [self setupLeftBarButtonItem: @"Beacon"];
//        self.searchTFD.placeholder = @"Name/MAC";
//    }
}

-(void)cannelAction
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [[BluetoothCenter shareInstance] disconnectCurrentPeripheral];
    [[BluetoothCenter shareInstance]stopConnectTimer];
}
//连接成功
-(void)bluetoothDidConnectedPeripheral:(CBPeripheral *)peripheral
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

-(void)didDiscoverCharacteristicsForService:(CBPeripheral *)peripheral
{
    //发送进入DFU
    [[BluetoothCenter shareInstance]enterDFU];

    DFURouter *router = [[DFURouter alloc]initWithNavigationController:self.navigationController];
    DFUStartViewController *vc = [router getStartViewController];
    [self.navigationController pushViewController:vc animated:NO];
    [vc openBluetoothConnector];
}
@end
